package com.yjhh.chdataservice.service;

import com.yjhh.chdataservice.InitDataFactory;
import com.yjhh.chdataservice.beans.*;
import com.yjhh.chdataservice.component.CommonDataComponent;
import com.yjhh.chdataservice.component.ESClientManager;
import com.yjhh.chdataservice.except.YJHHException;
import com.yjhh.chdataservice.util.CommonResultData;
import com.yjhh.chdataservice.util.DataTools;
import lombok.extern.log4j.Log4j;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.filter.InternalFilter;
import org.elasticsearch.search.aggregations.bucket.filters.InternalFilters;
import org.elasticsearch.search.aggregations.bucket.range.InternalRange;
import org.elasticsearch.search.aggregations.bucket.range.RangeAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static org.elasticsearch.index.query.QueryBuilders.*;

/**
 * 示范项目业务逻辑实现类
 */
@Service
@Log4j2
public class DemoProServiceImpl implements DemoProService {

    @Autowired
    private ESClientManager esClientManager;

    @Autowired
    private InitDataFactory initDataFactory;

    @Autowired
    private CommonDataComponent commonDataComponent;

    @Value("${point.scale.range}")
    private String pointScaleRange;

    @Value("${dict.industry.dictid}")
    private String industryDictid;

    @Value("${dict.feautrestype.dictid}")
    private String feautrestypeDictid;

    @Override
    public CommonResultData<List<DemoProBaseInfoVo>> getDemoProBaseInfoList(String areaCode, String pointName) throws YJHHException {
        //1.获取areaCode所在部门
        DeptBean sysDeptInfo = commonDataComponent.getSysDeptInfo(areaCode);
        if (sysDeptInfo == null) {
            return new CommonResultData<>(HttpStatus.OK.value(), "no data", null);
        }
        BoolQueryBuilder areacodequery = boolQuery().must(prefixQuery("deptno.keyword", sysDeptInfo.getDeptno()));
        areacodequery.must(termQuery("deletestate", "0"));
        if (StringUtils.isNotBlank(pointName)) {
            //整合三者过滤条件（OR）
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            areacodequery.must(boolQueryBuilder);
            boolQueryBuilder.should(matchPhraseQuery("pointname", StringUtils.trim(pointName)))
                    .should(matchPhraseQuery("city", StringUtils.trim(pointName)))
                    .should(matchPhraseQuery("country", StringUtils.trim(pointName)))
                    .should(matchPhraseQuery("town", StringUtils.trim(pointName)));
        }
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("proj_demonstrationitem_inf").setTypes("proj_demonstrationitem")
                .setSize(5000);
        searchRequestBuilder.setQuery(areacodequery);

        System.out.println("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        System.out.println("response=" + searchResponse.toString());

        SearchHit[] searchHits = searchResponse.getHits().getHits();

        List<DemoProBaseInfoVo> list = new ArrayList<>();
        for (SearchHit searchHit : searchHits) {
            Map<String, Object> searchHitSource = searchHit.getSource();

            //----------组装交通位置---------
            String trafficPosition = getTrafficPosition(searchHitSource);

            //---------行政位置---------------
            String deptPosition = getDeptPosition(searchHitSource);


            list.add(new DemoProBaseInfoVo(
                    DataTools.convertToStr(searchHitSource.get("demonstrationitem_id")),
                    DataTools.convertToStr(searchHitSource.get("pointid")),
                    DataTools.convertToStr(searchHitSource.get("pointname")),
                    trafficPosition,
                    deptPosition,
                    commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("b_demo_sqjcdzz"))),
                    commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("b_demo_cmwyh"))),
                    commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("b_demo_jmwyh"))),
                    commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("b_demo_sqfwzx"))),
                    commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("b_demo_wygs"))),
                    StringUtils.isBlank(DataTools.convertToStr(searchHitSource.get("pointx"))) ? 0.0 : Double
                            .parseDouble
                                    (DataTools.convertToStr(searchHitSource.get("pointx"))),
                    StringUtils.isBlank(DataTools.convertToStr(searchHitSource.get("pointy"))) ? 0.0 : Double
                            .parseDouble
                                    (DataTools.convertToStr(searchHitSource.get("pointy"))),
                    DataTools.convertToLone(searchHitSource.get("point_placement_allrs"))));
        }
        return new CommonResultData<>(HttpStatus.OK.value(), "suc", list);
    }

    private String getDeptPosition(Map<String, Object> searchHitSource) {
        //---------行政位置---------------
        String deptPosition = "";
        //靠城
        String demon_kcjxcname = DataTools.convertToStr(searchHitSource.get("demon_kcjxcname"));   //靠近城名称
        String demon_kcjxcgls = DataTools.convertToStr(searchHitSource.get("demon_kcjxcgls"));   //靠近城公里数

        //靠镇
        String demon_kzjzzxname = DataTools.convertToStr(searchHitSource.get("demon_kzjzzxname"));   //靠近镇名称
        String demon_kzzzxjl = DataTools.convertToStr(searchHitSource.get("demon_kzzzxjl"));   //靠近镇公里数

        //靠农业新型社区
        String demon_knysqname = DataTools.convertToStr(searchHitSource.get("demon_knysqname"));   //靠近农业新型社区名称
        String demon_knysqjl = DataTools.convertToStr(searchHitSource.get("demon_knysqjl"));   //靠近农业新型社区公里数

        //靠农业新型社区
        String demon_kzxcname = DataTools.convertToStr(searchHitSource.get("demon_kzxcname"));   //靠近村中心名称
        String demon_kzxcgls = DataTools.convertToStr(searchHitSource.get("demon_kzxcgls"));   //靠近村中心公里数

        if (StringUtils.isNotBlank(demon_kcjxcname) && StringUtils.isNotBlank(demon_kcjxcgls)) {
            deptPosition += "距" + demon_kcjxcname + "县城中心" + demon_kcjxcgls + "公里";
        } else if (StringUtils.isNotBlank(demon_kzjzzxname) && StringUtils.isNotBlank(demon_kzzzxjl)) {
            deptPosition += "距" + demon_kzjzzxname + "镇中心" + demon_kzzzxjl + "公里";
        } else if (StringUtils.isNotBlank(demon_knysqname) && StringUtils.isNotBlank(demon_knysqjl)) {
            deptPosition += "距" + demon_knysqname + "农业新型社区" + demon_knysqjl + "公里";
        } else if (StringUtils.isNotBlank(demon_kzxcname) && StringUtils.isNotBlank(demon_kzxcgls)) {
            deptPosition += "距" + demon_kzxcname + "村中心" + demon_kzxcgls + "公里";
        }
        return deptPosition;
    }

    private String getTrafficPosition(Map<String, Object> searchHitSource) {
        //----------组装交通位置---------
        String trafficPosition = "";

        //靠近高速
        String demon_kjgsjgsname = DataTools.convertToStr(searchHitSource.get("demon_kjgsjgsname"));   //靠近高速名称
        String demon_kjgsgls = DataTools.convertToStr(searchHitSource.get("demon_kjgsgls"));   //靠近高速公里数

        //靠近国道
        String demon_kjgdjgdname = DataTools.convertToStr(searchHitSource.get("demon_kjgdjgdname"));  //靠近国道名称
        String demon_kjgdgls = DataTools.convertToStr(searchHitSource.get("demon_kjgdgls"));  //靠近国道公里数

        //靠近其他交通干线
        String demon_kjqtjgxname = DataTools.convertToStr(searchHitSource.get("demon_kjqtjgxname"));  //靠近干线名称
        String demon_kjqtgls = DataTools.convertToStr(searchHitSource.get("demon_kjqtgls"));  //靠近干线公里数

        if (StringUtils.isNotBlank(demon_kjgsjgsname) && StringUtils.isNotBlank(demon_kjgsgls)) {
            trafficPosition += "距" + demon_kjgsjgsname + "高速" + demon_kjgsgls + "公里";
        } else if (StringUtils.isNotBlank(demon_kjgdjgdname) && StringUtils.isNotBlank(demon_kjgdgls)) {
            trafficPosition += "距" + demon_kjgsjgsname + "国道" + demon_kjgsgls + "公里";
        } else if (StringUtils.isNotBlank(demon_kjqtjgxname) && StringUtils.isNotBlank(demon_kjqtgls)) {
            trafficPosition += "距" + demon_kjqtjgxname + "干线" + demon_kjqtgls + "公里";
        }
        return trafficPosition;
    }

    @Override
    public CommonResultData<DemoProDetailInfoVo> getDemoProDetailInfo(String demonstrationitemId) throws YJHHException {
//获取搬迁户基础表
        QueryBuilder idsQueryBuilder = QueryBuilders.idsQuery().addIds(demonstrationitemId);
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("proj_demonstrationitem_inf").setTypes("proj_demonstrationitem").setQuery
                (idsQueryBuilder);

        log.info("reqeust: " + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response:" + searchResponse.toString());

        SearchHit[] hits = searchResponse.getHits().getHits();
        if (hits == null || hits.length <= 0) {
            return new CommonResultData<>(HttpStatus.OK.value(), "no data", null);
        }

        Map<String, Object> searchHitSource = hits[0].getSource();
        //----------组装交通位置---------
        String trafficPosition = getTrafficPosition(searchHitSource);

        //---------行政位置---------------
        String deptPosition = getDeptPosition(searchHitSource);

        String pointid = DataTools.convertToStr(searchHitSource.get("pointid"));
        DemoProDetailInfoVo demoProDetailInfoVo = new DemoProDetailInfoVo(
                DataTools.convertToStr(searchHitSource.get("demonstrationitem_id")),
                pointid,
                DataTools.convertToStr(searchHitSource.get("pointname")),
                trafficPosition,
                deptPosition,
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("b_demo_sqjcdzz"))),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("b_demo_cmwyh"))),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("b_demo_jmwyh"))),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("b_demo_sqfwzx"))),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("b_demo_wygs"))),
                DataTools.convertToStr(searchHitSource.get("pointaddress")),
                DataTools.convertToStr(searchHitSource.get("demon_xmjj")),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("b_structuretype"))) + " " +
                        commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("b_pointcommunitytype"))),
                StringUtils.isBlank(DataTools.convertToStr(searchHitSource.get("pointx"))) ? 0.0 : Double
                        .parseDouble
                                (DataTools.convertToStr(searchHitSource.get("pointx"))),
                StringUtils.isBlank(DataTools.convertToStr(searchHitSource.get("pointy"))) ? 0.0 : Double
                        .parseDouble
                                (DataTools.convertToStr(searchHitSource.get("pointy"))),
                DataTools.convertToLone(searchHitSource.get("point_placement_allrs")));

        //示范项目社区公共服务
        demoProDetailInfoVo.setDemoProPublicServiceVo(new DemoProPublicServiceVo(
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("b_demo_cxdb"))),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("b_demo_xnh"))),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("b_demo_ylbx"))),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("b_demo_mzjz"))),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("b_demo_ldjybz"))),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("b_demo_jsfw"))),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("b_demo_jrfw"))),
                DataTools.convertToStr(searchHitSource.get("b_other"))));

        //配套产业信息
        demoProDetailInfoVo.setDemoProIndustryVoList(getDemoProIndustryVos(pointid));

        return new CommonResultData<>(HttpStatus.OK.value(), "suc", demoProDetailInfoVo);
    }

    /**
     * 获取配套产业列表信息
     *
     * @param pointid
     * @return
     */
    private List<DemoProIndustryVo> getDemoProIndustryVos(String pointid) {
        BoolQueryBuilder boolQueryBuilder = boolQuery().must(termQuery("demonstrationitem_id.keyword", pointid));
        boolQueryBuilder.must(termQuery("deletestate", "0"));
        SearchRequestBuilder requestBuilder = esClientManager.getESClient().prepareSearch("proj_support_inf").setTypes("proj_support")
                .setSize(10000);
        requestBuilder.setQuery(boolQueryBuilder);

        System.out.println("request=" + requestBuilder.toString());
        SearchResponse sr = requestBuilder.execute().actionGet();
        System.out.println("response=" + sr.toString());

        SearchHit[] searchHits = sr.getHits().getHits();

        List<DemoProIndustryVo> list = new ArrayList<>();
        for (SearchHit searchHit : searchHits) {
            Map<String, Object> hitSource = searchHit.getSource();
            String industryschedule = DataTools.convertToStr(hitSource.get("industryschedule"));

            String industryscheduleStr = "";
            if (StringUtils.equalsIgnoreCase("0", industryschedule)) {
                industryscheduleStr = "规划阶段";
            } else if (StringUtils.equalsIgnoreCase("1", industryschedule)) {
                industryscheduleStr = "建设阶段";
            } else if (StringUtils.equalsIgnoreCase("2", industryschedule)) {
                industryscheduleStr = "生产/运营阶段";
            }

            list.add(new DemoProIndustryVo(
                    DataTools.convertToStr(hitSource.get("supportid")),
                    DataTools.convertToStr(hitSource.get("industryname")),
                    DataTools.convertToStr(hitSource.get("pointdistance")),
                    industryscheduleStr,
                    commonDataComponent.getSysDicValueById(DataTools.convertToStr(hitSource.get("indusyrytype"))),
                    DataTools.convertToStr(hitSource.get("postcount")),
                    DataTools.convertToStr(hitSource.get("monthmoney"))));
        }
        return list;
    }

    @Override
    public CommonResultData<List<DemoProAttachVo>> getDemoProAttachInfoList(String demonstrationitemId) throws YJHHException {
        BoolQueryBuilder boolQueryBuilder = boolQuery().must(termQuery("proj_proid.keyword", demonstrationitemId));
        SearchRequestBuilder requestBuilder = esClientManager.getESClient().prepareSearch("proj_attach_inf").setTypes("pattach_inf")
                .setSize(10000);
        requestBuilder.setQuery(boolQueryBuilder);

        System.out.println("request=" + requestBuilder.toString());
        SearchResponse sr = requestBuilder.execute().actionGet();
        System.out.println("response=" + sr.toString());

        SearchHit[] searchHits = sr.getHits().getHits();

        List<DemoProAttachVo> list = new ArrayList<>();
        for (SearchHit searchHit : searchHits) {
            Map<String, Object> hitSource = searchHit.getSource();
            list.add(new DemoProAttachVo(
                    DataTools.convertToStr(hitSource.get("prat_attachid")),
                    DataTools.convertToStr(hitSource.get("prat_projid")),
                    DataTools.convertToStr(hitSource.get("facilities_name")),
                    DataTools.convertToStr(hitSource.get("prat_localpath")) +
                            DataTools.convertToStr(hitSource.get("prat_serverpath")) +
                            DataTools.convertToStr(hitSource.get("prat_localname"))
            ));
        }

        return new CommonResultData<>(HttpStatus.OK.value(), "suc", list);
    }

    @Override
    public CommonResultData<StatisticsDemoProVo> statisticsDemoPro(String areaCode, String category) throws YJHHException {
        //1.获取areaCode所在部门
        DeptBean sysDeptInfo = commonDataComponent.getSysDeptInfo(areaCode);
        if (sysDeptInfo == null) {
            return new CommonResultData<>(HttpStatus.OK.value(), "no data", null);
        }

        //统计类型（1：交通位置，2：行政位置，3：安置规模，4：区域分布，5：产业类型，6：就业岗位，7：产业脱贫10+，8：公共服务，9：一站式服务）
        StatisticsDemoProVo statisticsDemoProVo = new StatisticsDemoProVo();
        switch (category) {
            case "0": //0：所有类型
                statisticsDemoProVo.setJtwz(statisticsDemoProByJTWZ(sysDeptInfo));
                statisticsDemoProVo.setXzwz(statisticsDemoProByXZWZ(sysDeptInfo));
                statisticsDemoProVo.setAzgm(statisticsDemoProByAZGM(sysDeptInfo));
                statisticsDemoProVo.setQyfb(statisticsDemoProByArea(sysDeptInfo));
                statisticsDemoProVo.setCylx(statisticsDemoProByCYLX(sysDeptInfo));
                statisticsDemoProVo.setJygw(statisticsDemoProByJYGW(sysDeptInfo));
                statisticsDemoProVo.setCytp(statisticsDemoProByCYTP(sysDeptInfo));
                statisticsDemoProVo.setGgfw(statisticsDemoProByGGFW(sysDeptInfo));
                statisticsDemoProVo.setYzsfw(statisticsDemoProByYZSFW(sysDeptInfo));
            case "1"://1：交通位置
                statisticsDemoProVo.setJtwz(statisticsDemoProByJTWZ(sysDeptInfo));
                break;
            case "2"://2：行政位置
                statisticsDemoProVo.setXzwz(statisticsDemoProByXZWZ(sysDeptInfo));
                break;
            case "3"://3：安置规模
                statisticsDemoProVo.setAzgm(statisticsDemoProByAZGM(sysDeptInfo));
                break;
            case "4"://4：区域分布
                statisticsDemoProVo.setQyfb(statisticsDemoProByArea(sysDeptInfo));
                break;
            case "5"://5：产业类型
                statisticsDemoProVo.setCylx(statisticsDemoProByCYLX(sysDeptInfo));
                break;
            case "6"://6：就业岗位
                statisticsDemoProVo.setJygw(statisticsDemoProByJYGW(sysDeptInfo));
                break;
            case "7"://7：产业脱贫10+
                statisticsDemoProVo.setCytp(statisticsDemoProByCYTP(sysDeptInfo));
                break;
            case "8"://8：公共服务
                statisticsDemoProVo.setGgfw(statisticsDemoProByGGFW(sysDeptInfo));
                break;
            case "9"://9：一站式服务
                statisticsDemoProVo.setYzsfw(statisticsDemoProByYZSFW(sysDeptInfo));
                break;
        }

        return new CommonResultData<>(HttpStatus.OK.value(), "suc", statisticsDemoProVo);
    }

    private List<CommonNameValueVo<Long>> statisticsDemoProByJYGW(DeptBean sysDeptInfo) {
        BoolQueryBuilder areacodequery = boolQuery().must(termQuery("deletestate", "0"));
        areacodequery.must(termQuery("stype", "1"));
        areacodequery.must(termsQuery("deptid.keyword", sysDeptInfo.getDeptID()));
        areacodequery.filter(existsQuery("deptname.keyword"));

        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_pointprograming_inf").setTypes
                ("pointprograming_inf");

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.fetchSource(new String[]{"deptid",  //部门ID
                "deptname",  //部门名称
                "point_contruction_tsnly",  //特色农林业
                "point_contruction_mjxgy",//劳动密集型工业
                "point_contruction_xdfwy",  //现代服务业
                "point_contruction_lwsc",   //劳务输出
                "point_contruction_shbzdd",   //社会保障兜底
                "point_contruction_gyxgw",   //公益性岗位
                "point_contruction_zzcy",   //自助创业
                "point_contruction_tpgwqt"   //就业脱贫规划岗位其他
        }, null);
        searchSourceBuilder.query(areacodequery);
        searchSourceBuilder.size(10000);

        searchRequestBuilder.setSource(searchSourceBuilder);

        log.info("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response=" + searchResponse.toString());

        SearchHit[] hits = searchResponse.getHits().getHits();
        List<CommonNameValueVo<Long>> resultList = new ArrayList<>();
        for (SearchHit hit : hits) {
            Map<String, Object> source = hit.getSource();
            resultList.add(new CommonNameValueVo<Long>("特色农业", DataTools.convertToLone(DataTools.convertToStr(source.get("point_contruction_tsnly")))));
            resultList.add(new CommonNameValueVo<Long>("劳动密集型", DataTools.convertToLone(DataTools.convertToStr(source.get("point_contruction_mjxgy")))));
            resultList.add(new CommonNameValueVo<Long>("服务业", DataTools.convertToLone(DataTools.convertToStr(source.get("point_contruction_xdfwy")))));
            resultList.add(new CommonNameValueVo<Long>("劳务输出", DataTools.convertToLone(DataTools.convertToStr(source.get("point_contruction_lwsc")))));
            resultList.add(new CommonNameValueVo<Long>("兜底保障", DataTools.convertToLone(DataTools.convertToStr(source.get("point_contruction_shbzdd")))));
            resultList.add(new CommonNameValueVo<Long>("公益性", DataTools.convertToLone(DataTools.convertToStr(source.get("point_contruction_gyxgw")))));
            resultList.add(new CommonNameValueVo<Long>("自主创业", DataTools.convertToLone(DataTools.convertToStr(source.get("point_contruction_zzcy")))));
            resultList.add(new CommonNameValueVo<Long>("其他", DataTools.convertToLone(DataTools.convertToStr(source.get("point_contruction_tpgwqt")))));
        }
        if (resultList.size() <= 0) {
            resultList.add(new CommonNameValueVo<Long>("特色农业", 0L));
            resultList.add(new CommonNameValueVo<Long>("劳动密集型", 0L));
            resultList.add(new CommonNameValueVo<Long>("服务业", 0L));
            resultList.add(new CommonNameValueVo<Long>("劳务输出", 0L));
            resultList.add(new CommonNameValueVo<Long>("兜底保障", 0L));
            resultList.add(new CommonNameValueVo<Long>("公益性", 0L));
            resultList.add(new CommonNameValueVo<Long>("自主创业", 0L));
            resultList.add(new CommonNameValueVo<Long>("其他", 0L));
        }
        return resultList;
    }

    private List<CommonNameValueVo<Long>> statisticsDemoProByCYTP(DeptBean sysDeptInfo) {
        //初始化字典map
        List<String> dicValues = commonDataComponent.getSubDicValuesByPId(feautrestypeDictid);
        Map<String, Integer> dictMap = new HashMap<>();
        for (String dicValue : dicValues) {
            dictMap.put(dicValue, 0);
        }

        BoolQueryBuilder areacodequery = boolQuery().must(prefixQuery("deptno.keyword", sysDeptInfo.getDeptno()));
        areacodequery.must(termQuery("deletestate", "0"));
        areacodequery.must(existsQuery("feautrestype"));
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("proj_demonstrationitem_inf").setTypes("proj_demonstrationitem")
                .setSize(5000);
        searchRequestBuilder.setQuery(areacodequery);

        System.out.println("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        System.out.println("response=" + searchResponse.toString());

        SearchHit[] searchHits = searchResponse.getHits().getHits();

        for (SearchHit searchHit : searchHits) {
            Map<String, Object> hitSource = searchHit.getSource();
            String feautrestype = DataTools.convertToStr(hitSource.get("feautrestype"));
            List<String> dicValueList = commonDataComponent.getSysDicValueListById(feautrestype);
            //给map中追加值
            for (String dicValue : dicValueList) {
                dictMap.put(dicValue, dictMap.get(dicValue) + 1);
            }
        }

        //map转化为CommonNameValueVo
        List<CommonNameValueVo<Long>> resultList = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : dictMap.entrySet()) {
            resultList.add(new CommonNameValueVo(entry.getKey(), entry.getValue().longValue()));
        }

        //排序
        Collections.sort(resultList, (CommonNameValueVo<Long> o1, CommonNameValueVo<Long> o2) -> {
            return o2.getValue() <= o1.getValue() ? -1 : 1;
        });

        return resultList;
    }

    private List<CommonNameValueVo<Long>> statisticsDemoProByGGFW(DeptBean sysDeptInfo) {
        BoolQueryBuilder areacodequery = boolQuery().must(prefixQuery("deptno.keyword", sysDeptInfo.getDeptno()));
        areacodequery.must(termQuery("deletestate", "0"));
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("proj_demonstrationitem_inf").setTypes("proj_demonstrationitem")
                .setSize(0);
        searchRequestBuilder.setQuery(areacodequery);

        searchRequestBuilder.addAggregation(AggregationBuilders.filter("城乡低保", boolQuery().should(termQuery("b_demo_cxdb.keyword", "376")).should(termQuery("b_demo_cxdb.keyword", "377"))));
        searchRequestBuilder.addAggregation(AggregationBuilders.filter("新农合", boolQuery().should(termQuery("b_demo_xnh.keyword", "376")).should(termQuery("b_demo_xnh.keyword", "377"))));
        searchRequestBuilder.addAggregation(AggregationBuilders.filter("养老保险", boolQuery().should(termQuery("b_demo_ylbx.keyword", "376")).should(termQuery("b_demo_ylbx.keyword", "377"))));
        searchRequestBuilder.addAggregation(AggregationBuilders.filter("民政救助", boolQuery().should(termQuery("b_demo_mzjz.keyword", "376")).should(termQuery("b_demo_mzjz.keyword", "377"))));
        searchRequestBuilder.addAggregation(AggregationBuilders.filter("劳动就业保障", boolQuery().should(termQuery("b_demo_ldjybz.keyword", "376")).should(termQuery("b_demo_ldjybz.keyword", "377"))));
        searchRequestBuilder.addAggregation(AggregationBuilders.filter("计生服务管理", boolQuery().should(termQuery("b_demo_jsfw.keyword", "376")).should(termQuery("b_demo_jsfw.keyword", "377"))));
        searchRequestBuilder.addAggregation(AggregationBuilders.filter("金融服务", boolQuery().should(termQuery("b_demo_jrfw.keyword", "376")).should(termQuery("b_demo_jrfw.keyword", "377"))));
        searchRequestBuilder.addAggregation(AggregationBuilders.filter("其他", existsQuery("b_demo_cxdb.keyword")));

        System.out.println("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        System.out.println("response=" + searchResponse.toString());

        List<Aggregation> aggregations = searchResponse.getAggregations().asList();
        List<CommonNameValueVo<Long>> list = new ArrayList();
        for (Aggregation aggregation : aggregations) {
            InternalFilter internalFilter = (InternalFilter) aggregation;
            list.add(new CommonNameValueVo(internalFilter.getName(), internalFilter.getDocCount()));
        }

        //排序
        Collections.sort(list, (CommonNameValueVo<Long> o1, CommonNameValueVo<Long> o2) -> {
            return o2.getValue() <= o1.getValue() ? -1 : 1;
        });
        return list;
    }

    private List<CommonNameValueVo<Long>> statisticsDemoProByCYLX(DeptBean sysDeptInfo) {
        //1.获取areaCode所有子部门
        if (sysDeptInfo == null) {
            return new ArrayList<>();
        }
        List<String> subDicValues = commonDataComponent.getSubDicValuesByPId(industryDictid);

        List<IndustryInfoStaticsVo> industryInfoVos = new ArrayList<>();
        //转化数据格式为List<CommonNameValueVo<Long>>
        List<CommonNameValueVo<Long>> totalIndustryList = new ArrayList<>(subDicValues.parallelStream()
                .map(dictName -> new CommonNameValueVo<Long>(dictName, 0L))
                .collect(Collectors.toList()));

        //2、通过聚合查询获取所有聚合后的区域和产业分类数量
        BoolQueryBuilder areacodequery = boolQuery().must(prefixQuery("deptno.keyword", sysDeptInfo.getDeptno()));
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("proj_support_inf").setTypes("proj_support")
                .setSize(0);
        searchRequestBuilder.setQuery(areacodequery);

        TermsAggregationBuilder typeAgg = AggregationBuilders.terms("typeGroup").field("indusyrytype.keyword").size(100);

        searchRequestBuilder.addAggregation(typeAgg);

        System.out.println("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        System.out.println("response=" + searchResponse.toString());

        StringTerms areaGroup = (StringTerms) searchResponse.getAggregations().asList().get(0);
        List<StringTerms.Bucket> areaGroupBuckets = areaGroup.getBuckets();

        for (StringTerms.Bucket bucket : areaGroupBuckets) {
            String indusyryType = bucket.getKeyAsString();
            //给具体的产业赋值
            long docCount = bucket.getDocCount();
            if (StringUtils.isNotBlank(indusyryType)) {
                //由于示范产业类型有多选类型，所以需要拆分计算
                String[] indusyryTypeArray = StringUtils.split(indusyryType, ",");
                for (String indusyryTypeCode : indusyryTypeArray) {
                    String indusyryTypeStr = commonDataComponent.getSysDicValueById(indusyryTypeCode);
                    //合计值计算
                    totalIndustryList.forEach(industry -> {
                        if (industry.getName().equalsIgnoreCase(indusyryTypeStr)) {
                            industry.setValue(industry.getValue() + docCount);
                        }
                    });
                }
            }
        }

        return totalIndustryList;
    }

    private List<CommonNameValueVo<Long>> statisticsDemoProByArea(DeptBean sysDeptInfo) {
        BoolQueryBuilder areacodequery = boolQuery().must(prefixQuery("deptno.keyword", sysDeptInfo.getDeptno()));
        areacodequery.must(termQuery("deletestate", "0"));
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("proj_demonstrationitem_inf").setTypes("proj_demonstrationitem")
                .setSize(5000);
        searchRequestBuilder.setQuery(areacodequery);

        System.out.println("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        System.out.println("response=" + searchResponse.toString());

        SearchHit[] searchHits = searchResponse.getHits().getHits();

        String sb = "陕北";
        CommonNameValueVo<Long> north = new CommonNameValueVo<>(sb, 0L);
        String gz = "关中";
        CommonNameValueVo<Long> middle = new CommonNameValueVo<>(gz, 0L);
        String sn = "陕南";
        CommonNameValueVo<Long> south = new CommonNameValueVo<>(sn, 0L);

        List<CommonNameValueVo<Long>> list = new ArrayList<>();
        list.add(north);
        list.add(middle);
        list.add(south);

        for (SearchHit searchHit : searchHits) {
            Map<String, Object> searchHitSource = searchHit.getSource();
            String city = DataTools.convertToStr(searchHitSource.get("city"));
            String deptid = DataTools.convertToStr(searchHitSource.get("deptid"));
            if (StringUtils.isNotBlank(deptid)) {
                DeptBean deptBean = commonDataComponent.getDeptByDeptId(deptid);
                if (deptBean == null) {
                    continue;
                }
                String areaType = deptBean.getAreaType();
                if (StringUtils.equalsIgnoreCase(sb, areaType)) {
                    north.setValue(north.getValue() + 1);
                } else if (StringUtils.equalsIgnoreCase(gz, areaType)) {
                    middle.setValue(middle.getValue() + 1);
                } else if (StringUtils.equalsIgnoreCase(sn, areaType)) {
                    south.setValue(south.getValue() + 1);
                }
            } else {
                DeptBean deptBean = commonDataComponent.getDeptByDeptName(city);
                if (deptBean == null) {
                    continue;
                }
                String areaType = deptBean.getAreaType();
                if (StringUtils.equalsIgnoreCase(sb, areaType)) {
                    north.setValue(north.getValue() + 1);
                } else if (StringUtils.equalsIgnoreCase(gz, areaType)) {
                    middle.setValue(middle.getValue() + 1);
                } else if (StringUtils.equalsIgnoreCase(sn, areaType)) {
                    south.setValue(south.getValue() + 1);
                }
            }
        }

        return list;
    }

    //安置规模
    private List<CommonNameValueVo<Long>> statisticsDemoProByAZGM(DeptBean sysDeptInfo) {
        BoolQueryBuilder areacodequery = boolQuery().must(prefixQuery("deptno.keyword", sysDeptInfo.getDeptno()));
        areacodequery.must(termQuery("deletestate", "0"));
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("proj_demonstrationitem_inf").setTypes("proj_demonstrationitem")
                .setSize(0);
        searchRequestBuilder.setQuery(areacodequery);

        //根据配置文件解析人口规模分段
        if (StringUtils.isBlank(pointScaleRange)) {
            return new ArrayList<>();
        }

        RangeAggregationBuilder rangeAggregationBuilder = AggregationBuilders.range("pointScale")
                .field("point_placement_allrs");

        StringTokenizer tokenParser = new StringTokenizer(pointScaleRange, ",");
        while (tokenParser.hasMoreTokens()) {
            String range = tokenParser.nextToken();
            String[] split = range.split("-");
            if (split[0].equals("5001")) {
                rangeAggregationBuilder.addRange("5000以上", Double.parseDouble(split[0]), Double.parseDouble(split[1]));
            } else {
                rangeAggregationBuilder.addRange(range + "", Double.parseDouble(split[0]), Double.parseDouble(split[1]));
            }
        }
        rangeAggregationBuilder.missing(0);

        searchRequestBuilder.addAggregation(rangeAggregationBuilder);

        System.out.println("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        System.out.println("response=" + searchResponse.toString());

        Aggregations aggregations = searchResponse.getAggregations();
        InternalRange aggregation = (InternalRange) aggregations.asList().get(0);

        List<InternalRange.Bucket> buckets = aggregation.getBuckets();
        List<CommonNameValueVo<Long>> resultList = new ArrayList<>();

        for (InternalRange.Bucket bucket : buckets) {
            resultList.add(new CommonNameValueVo<Long>(bucket.getKeyAsString(), bucket.getDocCount()));
        }

        return resultList;
    }

    //一站式服务
    private List<CommonNameValueVo<Long>> statisticsDemoProByYZSFW(DeptBean sysDeptInfo) {
        BoolQueryBuilder areacodequery = boolQuery().must(prefixQuery("deptno.keyword", sysDeptInfo.getDeptno()));
        areacodequery.must(termQuery("deletestate", "0"));
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("proj_demonstrationitem_inf").setTypes("proj_demonstrationitem")
                .setSize(0);
        searchRequestBuilder.setQuery(areacodequery);

        //396 表示 无
        searchRequestBuilder.addAggregation(AggregationBuilders.terms("demo_sqfwzx").field("b_demo_sqfwzx.keyword").missing("396"));

        System.out.println("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        System.out.println("response=" + searchResponse.toString());

        Aggregations aggregations = searchResponse.getAggregations();
        StringTerms aggregation = (StringTerms) aggregations.asList().get(0);
        List<StringTerms.Bucket> buckets = aggregation.getBuckets();

        List<CommonNameValueVo<Long>> list = new ArrayList();
        CommonNameValueVo<Long> existObj = new CommonNameValueVo<Long>("有", 0L);
        CommonNameValueVo<Long> noObj = new CommonNameValueVo<Long>("无", 0L);
        for (StringTerms.Bucket bucket : buckets) {
            String keyAsStr = bucket.getKeyAsString();
            if (StringUtils.equalsIgnoreCase("396", keyAsStr)) {
                existObj.setValue(existObj.getValue() + bucket.getDocCount());
            } else {
                noObj.setValue(noObj.getValue() + bucket.getDocCount());
            }
        }

        list.add(existObj);
        list.add(noObj);

        //排序
        Collections.sort(list, (CommonNameValueVo<Long> o1, CommonNameValueVo<Long> o2) -> {
            return o2.getValue() <= o1.getValue() ? -1 : 1;
        });

        return list;
    }

    //按行政位置统计
    private List<CommonNameValueVo<Long>> statisticsDemoProByXZWZ(DeptBean sysDeptInfo) {
        BoolQueryBuilder areacodequery = boolQuery().must(prefixQuery("deptno.keyword", sysDeptInfo.getDeptno()));
        areacodequery.must(termQuery("deletestate", "0"));
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("proj_demonstrationitem_inf").setTypes("proj_demonstrationitem")
                .setSize(0);
        searchRequestBuilder.setQuery(areacodequery);

        searchRequestBuilder.addAggregation(AggregationBuilders.filter("靠城", existsQuery("demon_kcjxcname.keyword")));
        searchRequestBuilder.addAggregation(AggregationBuilders.filter("靠镇", existsQuery("demon_kzjzzxname.keyword")));
        searchRequestBuilder.addAggregation(AggregationBuilders.filter("靠农业新型社区", existsQuery("demon_knysqname.keyword")));
        searchRequestBuilder.addAggregation(AggregationBuilders.filter("靠中心村", existsQuery("demon_kzxcname.keyword")));

        System.out.println("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        System.out.println("response=" + searchResponse.toString());

        List<Aggregation> aggregations = searchResponse.getAggregations().asList();
        List<CommonNameValueVo<Long>> list = new ArrayList();
        for (Aggregation aggregation : aggregations) {
            InternalFilter internalFilter = (InternalFilter) aggregation;
            list.add(new CommonNameValueVo(internalFilter.getName(), internalFilter.getDocCount()));
        }

        //排序
        Collections.sort(list, (CommonNameValueVo<Long> o1, CommonNameValueVo<Long> o2) -> {
            return o2.getValue() <= o1.getValue() ? -1 : 1;
        });
        return list;
    }

    /**
     * 按交通位置统计示范项目个数
     *
     * @param sysDeptInfo
     * @return
     */
    private List<CommonNameValueVo<Long>> statisticsDemoProByJTWZ(DeptBean sysDeptInfo) {
        BoolQueryBuilder areacodequery = boolQuery().must(prefixQuery("deptno.keyword", sysDeptInfo.getDeptno()));
        areacodequery.must(termQuery("deletestate", "0"));
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("proj_demonstrationitem_inf").setTypes("proj_demonstrationitem")
                .setSize(0);
        searchRequestBuilder.setQuery(areacodequery);

        searchRequestBuilder.addAggregation(AggregationBuilders.filter("近高速", existsQuery("demon_kjgsjgsname.keyword")));
        searchRequestBuilder.addAggregation(AggregationBuilders.filter("近国道", existsQuery("demon_kjgdjgdname.keyword")));
        searchRequestBuilder.addAggregation(AggregationBuilders.filter("近其他干线", existsQuery("demon_kjqtjgxname.keyword")));

        System.out.println("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        System.out.println("response=" + searchResponse.toString());

        List<Aggregation> aggregations = searchResponse.getAggregations().asList();
        List<CommonNameValueVo<Long>> list = new ArrayList();
        for (Aggregation aggregation : aggregations) {
            InternalFilter internalFilter = (InternalFilter) aggregation;
            list.add(new CommonNameValueVo(internalFilter.getName(), internalFilter.getDocCount()));
        }

        //排序
        Collections.sort(list, (CommonNameValueVo<Long> o1, CommonNameValueVo<Long> o2) -> {
            return o2.getValue() <= o1.getValue() ? -1 : 1;
        });
        return list;
    }
}
